import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getCurrentUser();
    if (!user || user.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: '需要管理员权限' },
        { status: 403 }
      );
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const range = searchParams.get('range') || '30d';
    
    // 计算日期范围
    let days = 30;
    if (range === '7d') days = 7;
    else if (range === '90d') days = 90;
    else if (range === '1y') days = 365;

    // 获取用户增长数据
    const userGrowth = await query(
      `SELECT 
        DATE_FORMAT(created_at, '%Y-%m') as month,
        COUNT(*) as count
      FROM users
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
      GROUP BY DATE_FORMAT(created_at, '%Y-%m')
      ORDER BY month`,
      [days]
    );

    // 获取题型热度
    const topicPopularity = await query(
      `SELECT 
        topic_id as topic,
        COUNT(*) as sessions
      FROM practice_sessions
      WHERE started_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
      GROUP BY topic_id
      ORDER BY sessions DESC
      LIMIT 10`,
      [days]
    );

    // 获取正确率趋势
    const accuracyTrend = await query(
      `SELECT 
        DATE_FORMAT(started_at, '%Y-%m-%d') as date,
        AVG(CASE WHEN question_count > 0 THEN (correct_count / question_count * 100) ELSE 0 END) as accuracy
      FROM practice_sessions
      WHERE started_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
      GROUP BY DATE_FORMAT(started_at, '%Y-%m-%d')
      ORDER BY date`,
      [days]
    );

    // 获取年级分布
    const gradeDistribution = await query(
      `SELECT 
        CONCAT('年级', grade) as grade,
        COUNT(*) as count
      FROM user_profiles
      GROUP BY grade
      ORDER BY grade`
    );

    return NextResponse.json({
      success: true,
      data: {
        userGrowth: userGrowth || [],
        topicPopularity: topicPopularity || [],
        accuracyTrend: accuracyTrend || [],
        gradeDistribution: gradeDistribution || []
      }
    });

  } catch (error) {
    console.error('获取分析数据错误:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '获取分析数据失败' 
      },
      { status: 500 }
    );
  }
}

